﻿Imports SIGI.Common.BE
Imports SIGI.Common.CommonDefinitions

Public Class frmABMUsers

#Region "<< -Attributes- >>"
    Private Const _UserName As String = "Nombre Usuario"
    Private Const _DocNumber As String = "Número Documento"

    Private _Users As List(Of UserBE) = Nothing
    Private _SexList As List(Of SexBE) = Nothing
    Private _DocTypeList As List(Of DocumentTypeBE) = Nothing
    Private _CountryList As List(Of CountryBE) = Nothing
    Private _QuestionList As List(Of QuestionBE) = Nothing
    Private _UserController As UsersController = New UsersController
#End Region

#Region "<< -Events- >>"

    Private Sub frmABMUsers_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim wProfileController As ProfileController = Nothing
        Dim wSexController As SexController = Nothing
        Dim wCountryController As CountryController = Nothing
        Dim wDocTypeController As DocumentTypeController = Nothing
        Dim wQuestionController As QuestionController = Nothing
        Dim wCountry As CountryBE = Nothing

        Try
            'Asigno los eventos a la botonera principal
            AddHandler btnNew.Click, AddressOf btnNew_Click
            AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
            AddHandler btnDelete.Click, AddressOf btnDelete_Click
            AddHandler btnSave.Click, AddressOf btnSave_Click
            AddHandler btnCancel.Click, AddressOf btnCancel_Click
            AddHandler txtDocNumber.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress

            cmbFilterType.SelectedIndex = 0
            'Cargo los Perfiles
            wProfileController = New ProfileController
            cmbFilter.ValueMember = "Id"
            cmbFilter.DisplayMember = "Description"
            cmbFilter.DataSource = wProfileController.Search()
            If cmbFilter.Items.Count > 0 Then cmbFilter.SelectedIndex = 0
            cmbProfile.ValueMember = "Id"
            cmbProfile.DisplayMember = "Description"
            cmbProfile.DataSource = wProfileController.Search()
            If cmbProfile.Items.Count > 0 Then cmbProfile.SelectedIndex = 0

            'Cargo los usuarios no dados de baja.
            LoadUsers(False)

            'Cargo la lista de Sexos.
            wSexController = New SexController
            _SexList = wSexController.Search()
            cmbSex.ValueMember = "Id"
            cmbSex.DisplayMember = "Description"
            cmbSex.DataSource = _SexList
            If _SexList.Count > 0 Then cmbSex.SelectedIndex = 0

            'Cargo la lista de tipos de documentos.
            wDocTypeController = New DocumentTypeController
            _DocTypeList = wDocTypeController.Search()
            cmbDocType.ValueMember = "Id"
            cmbDocType.DisplayMember = "Description"
            cmbDocType.DataSource = _DocTypeList
            If _DocTypeList.Count > 0 Then cmbDocType.SelectedIndex = 0

            'Cargo la lista de Países.
            wCountryController = New CountryController
            _CountryList = wCountryController.Search()
            wCountry = New CountryBE
            wCountry.Id = 0
            wCountry.Description = "Sin Selección"
            _CountryList.Insert(0, wCountry)
            cmbCountry.ValueMember = "Id"
            cmbCountry.DisplayMember = "Description"
            cmbCountry.DataSource = _CountryList
            cmbCountry.SelectedIndex = 0

            'Cargo la lista de preguntas.
            wQuestionController = New QuestionController
            _QuestionList = wQuestionController.Search()
            cmbQuestion.ValueMember = "Id"
            cmbQuestion.DisplayMember = "Description"
            cmbQuestion.DataSource = _QuestionList
            If _QuestionList.Count > 0 Then cmbQuestion.SelectedIndex = 0

            'Asignación de eventos genéricos.
            AddHandler txtDocNumber.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress

            'Muestra la info del primer usuario
            If _Users.Count > 0 Then LoadUserData(_Users(0))
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbFilterType_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbFilterType.SelectedIndexChanged
        Try
            If cmbFilterType.Text = _UserName Or cmbFilterType.Text = _DocNumber Then
                txtFilter.Text = String.Empty
                txtFilter.Visible = True
                txtFilter.Focus()
                txtFilter.SelectAll()
                cmbFilter.Visible = False

                If cmbFilterType.Text = _DocNumber Then
                    'Para que permita ingresar sólo números
                    AddHandler txtFilter.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress
                Else
                    RemoveHandler txtFilter.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress
                End If
            Else
                cmbFilter.Visible = True
                cmbFilter.Focus()
                txtFilter.Visible = False
            End If

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs)
        Me.Close()
    End Sub

    Private Sub gridUsers_RowCellClick(sender As System.Object, e As DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs) Handles GridView1.RowCellClick
        Dim wRowIdx As Integer = 0
        Dim wUser As UserBE = Nothing

        Try
            wRowIdx = e.RowHandle
            'Obtengo los datos del usuario en la lista de usuarios.
            wUser = _Users(wRowIdx)
            LoadUserData(wUser)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbCountry_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbCountry.SelectedValueChanged
        Dim wCountryId As Integer = 0

        Try
            wCountryId = Convert.ToInt32(cmbCountry.SelectedValue)
            GenericMethods.GetProvinceByCountryId(wCountryId, cmbProvince)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbProvince_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbProvince.SelectedValueChanged
        Dim wProvinceId As Integer = 0

        Try
            wProvinceId = Convert.ToInt32(cmbProvince.SelectedValue)
            GenericMethods.GetCityByProvinceId(wProvinceId, cmbCity)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        Dim wFilterUsers As List(Of UserBE) = Nothing

        Try
            'Filtro el contenido de la grilla según el filtro utilizado.
            If cmbFilterType.Text = _UserName Then
                If String.IsNullOrEmpty(txtFilter.Text.Trim) Then Return
                'Filtro la grilla por el nombre de usuario.
                wFilterUsers = _Users.Where(Function(u) u.UserName.StartsWith(txtFilter.Text.Trim)).ToList()
            ElseIf cmbFilterType.Text = _DocNumber Then
                If String.IsNullOrEmpty(txtFilter.Text.Trim) Then Return
                'Filtro por dni de usuario
                wFilterUsers = _Users.Where(Function(u) u.DocumentNumber.ToString.StartsWith(txtFilter.Text.Trim)).ToList()
            Else
                'Filtro por perfil.
                wFilterUsers = _Users.Where(Function(u) u.Profile.Id = cmbFilter.SelectedValue).ToList()
            End If

            BindingSource.DataSource = wFilterUsers
            BindingSource.ResetBindings(True)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub txtCuit_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtCuit.KeyPress
        Dim wAscii As Integer = 0

        Try
            wAscii = Convert.ToInt32(e.KeyChar)
            If wAscii = Keys.Back Or wAscii = Keys.Delete Then Return

            'Estructura del CUIT/L
            '(*) La primer parte se compone de dos dígitos: 20 para varones, 27 para mujeres.
            '(*) La segunda parte se encuentra integrada por ocho dígitos.
            '(*) La tercer parte del número esta compuesta por un dígito.
            If txtCuit.TextLength = 11 Then
                'xx-xxxxxxxx
                txtCuit.Text = String.Concat(txtCuit.Text, "-")
                txtCuit.SelectionStart = txtCuit.TextLength
            End If

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbSex_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbSex.SelectedValueChanged
        Try
            If _Behavior <> CRUD.Read Then
                If cmbSex.Text.ToLower = "femenino" Then
                    txtCuit.Text = "27-"
                ElseIf cmbSex.Text.ToLower = "masculino" Then
                    txtCuit.Text = "20-"
                End If
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub chkInactiveUsers_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkInactiveUsers.CheckedChanged
        Try
            LoadUsers(chkInactiveUsers.Checked)
            btnDelete.Enabled = Not chkInactiveUsers.Checked
            gridUsers.ContextMenuStrip = IIf(chkInactiveUsers.Checked, ContextMenuInactiveUsers, Nothing)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnNew_Click(sender As System.Object, e As System.EventArgs)
        Try
            ButtonController(btnNew.Name)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs)
        Try
            ButtonController(btnUpdate.Name)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs)
        Try
            If CloseUserAccount() Then
                _MsgBox.ShowMessage("ABM Usuarios", "Usuario dado de baja con éxito",
                                        frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
                LoadUsers(chkInactiveUsers.Checked)
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs)
        Try
            If _Behavior = CRUD.Insert Then
                If InsertUser() Then
                    _MsgBox.ShowMessage("ABM Usuarios", "Los datos han sido guardados correctamente",
                                        frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
                    ButtonController(btnSave.Name)
                    LoadUsers(chkInactiveUsers.Checked)
                End If
            End If
            If _Behavior = CRUD.Update Then
                If UpdateUser() Then
                    _MsgBox.ShowMessage("ABM Usuarios", "Usuario actualizado con éxito",
                                        frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
                    ButtonController(btnSave.Name)
                    LoadUsers(chkInactiveUsers.Checked)
                End If
            End If

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs)
        Try
            ButtonController(btnCancel.Name)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub ReactivarUsuariosToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ReactivarUsuariosToolStripMenuItem.Click
        Dim wUser As UserBE = Nothing
        Try

            If GridView1.RowCount = 0 Then Return

            wUser = _Users.Find(Function(u) u.UserName = GridView1.GetFocusedRowCellValue("UserName"))
            wUser.EndDate = Nothing
            wUser.AccountCloseMotive = String.Empty
            _UserController.Update(wUser)
            _MsgBox.ShowMessage("ABM Usuarios", "Usuario reactivado exitósamente", frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
            LoadUsers(chkInactiveUsers.Checked)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub VerMotivoDeBajaDeUsuarioToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles VerMotivoDeBajaDeUsuarioToolStripMenuItem.Click
        Dim wInputBox As frmInputVisorBox = Nothing
        Dim wUser As UserBE = Nothing

        Try
            If GridView1.RowCount = 0 Then Return

            wUser = _Users.Find(Function(u) u.UserName = GridView1.GetFocusedRowCellValue("UserName"))
            wInputBox = New frmInputVisorBox
            wInputBox.ShowBox("Motivo de Baja de Usuario", frmInputVisorBox.Behavior.Read, wUser.AccountCloseMotive)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnRemoveFilter_Click(sender As System.Object, e As System.EventArgs) Handles btnRemoveFilter.Click
        Try
            LoadUsers(chkInactiveUsers.Checked)
            txtFilter.Text = String.Empty
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub
#End Region

#Region "<< -Methods- >>"
    Private Sub LoadUsers(pNotActives As Boolean)
        _Users = _UserController.Search(pNotActives)
        BindingSource.DataSource = _Users
    End Sub

    Private Sub LoadUserData(pUser As UserBE)
        Dim wProvinceList As List(Of ProvinceBE) = Nothing
        Dim wCityList As List(Of CityBE) = Nothing

        If _Behavior <> CRUD.Read Then Return

        For Each wCtrl As Control In grpUserData.Controls
            If TypeOf wCtrl Is TextBox Then
                DirectCast(wCtrl, TextBox).ReadOnly = True
                DirectCast(wCtrl, TextBox).Visible = True
            End If
            If TypeOf wCtrl Is ComboBox Then DirectCast(wCtrl, ComboBox).Visible = False
        Next

        cmbProfile.SelectedValue = pUser.Profile.Id
        txtProfile.Text = pUser.Profile.Description
        txtUserName.Text = pUser.UserName
        txtPassword.Text = pUser.Password
        txtConfirmPassword.Text = pUser.Password
        txtQuestion.Text = pUser.Question.Description
        txtAnswer.Text = pUser.Answer
        txtName.Text = pUser.Name
        txtDocType.Text = pUser.DocumentType.Description
        txtDocNumber.Text = pUser.DocumentNumber
        txtSex.Text = pUser.Sex.Description
        txtCuit.Text = pUser.Cuit
        If Not pUser.Country Is Nothing AndAlso pUser.Country.Id.HasValue Then
            txtCountry.Text = pUser.Country.Description
        End If
        If Not pUser.Province Is Nothing AndAlso pUser.Province.Id.HasValue Then
            txtProvince.Text = pUser.Province.Description
        End If
        If Not pUser.City Is Nothing AndAlso pUser.City.Id.HasValue Then
            txtCity.Text = pUser.City.Description
        End If
        txtDirection.Text = pUser.Direction
        txtPostalCode.Text = pUser.PostalCode
        txtPhone.Text = pUser.Phone
        txtCelphone.Text = pUser.Celphone
        txtEmail.Text = pUser.Email
    End Sub

    Private Sub ButtonController(pButton As String)
        Select Case pButton
            Case btnNew.Name
                For Each wCtrl As Control In grpUserData.Controls
                    If TypeOf wCtrl Is TextBox Then
                        DirectCast(wCtrl, TextBox).ReadOnly = False
                        DirectCast(wCtrl, TextBox).Text = String.Empty
                    End If
                    If TypeOf wCtrl Is ComboBox Then
                        DirectCast(wCtrl, ComboBox).Enabled = True
                        DirectCast(wCtrl, ComboBox).Visible = True
                    End If
                Next
                txtProfile.Visible = False
                txtQuestion.Visible = False
                txtDocType.Visible = False
                txtSex.Visible = False
                txtCountry.Visible = False
                txtProvince.Visible = False
                txtCity.Visible = False

                btnNew.Enabled = False
                btnUpdate.Enabled = False
                btnDelete.Enabled = False
                btnCancel.Enabled = True
                btnSave.Enabled = True

                btnSearch.Enabled = False
                btnRemoveFilter.Enabled = False

                chkInactiveUsers.Enabled = False

                If cmbSex.Text.ToLower = "femenino" Then
                    txtCuit.Text = "27-"
                ElseIf cmbSex.Text.ToLower = "masculino" Then
                    txtCuit.Text = "20-"
                End If

                _Behavior = CRUD.Insert

            Case btnUpdate.Name
                For Each wCtrl As Control In grpUserData.Controls
                    If TypeOf wCtrl Is TextBox Then
                        'Sólo habilito los texto box que no sean el de nombre de usuario.
                        If wCtrl.Name <> txtUserName.Name Then DirectCast(wCtrl, TextBox).ReadOnly = False
                    End If
                    If TypeOf wCtrl Is ComboBox Then
                        DirectCast(wCtrl, ComboBox).Enabled = True
                        DirectCast(wCtrl, ComboBox).Visible = True
                    End If
                Next
                txtProfile.Visible = False
                txtQuestion.Visible = False
                txtDocType.Visible = False
                txtSex.Visible = False
                txtCountry.Visible = False
                txtProvince.Visible = False
                txtCity.Visible = False

                btnNew.Enabled = False
                btnUpdate.Enabled = False
                btnDelete.Enabled = False
                btnCancel.Enabled = True
                btnSave.Enabled = True

                btnSearch.Enabled = False
                btnRemoveFilter.Enabled = False

                chkInactiveUsers.Enabled = False

                _Behavior = CRUD.Update

            Case btnDelete.Name
                _Behavior = CRUD.Delete
                chkInactiveUsers.Enabled = False

            Case btnSave.Name
                btnNew.Enabled = True
                btnUpdate.Enabled = True
                btnDelete.Enabled = True
                btnCancel.Enabled = False
                btnSave.Enabled = False

                btnSearch.Enabled = True
                btnRemoveFilter.Enabled = True

                chkInactiveUsers.Enabled = True

                For Each wCtrl As Control In grpUserData.Controls
                    If TypeOf wCtrl Is TextBox Then
                        DirectCast(wCtrl, TextBox).ReadOnly = True
                        DirectCast(wCtrl, TextBox).Visible = True
                    End If
                    If TypeOf wCtrl Is ComboBox Then DirectCast(wCtrl, ComboBox).Visible = False
                Next

                _Behavior = CRUD.Read
            Case btnCancel.Name
                btnNew.Enabled = True
                btnUpdate.Enabled = True
                btnDelete.Enabled = True
                btnCancel.Enabled = False
                btnSave.Enabled = False

                chkInactiveUsers.Enabled = True

                For Each wCtrl As Control In grpUserData.Controls
                    If TypeOf wCtrl Is TextBox Then
                        DirectCast(wCtrl, TextBox).ReadOnly = True
                        DirectCast(wCtrl, TextBox).Visible = True
                    End If
                    If TypeOf wCtrl Is ComboBox Then DirectCast(wCtrl, ComboBox).Visible = False
                Next

                btnSearch.Enabled = True
                btnRemoveFilter.Enabled = True

                _Behavior = CRUD.Read
            Case Else
                _Behavior = CRUD.Read
        End Select
    End Sub

    Private Function ValidateRequiredFields() As Boolean
        'Verifico que se hayan ingresado los datos obligatorios
        If String.IsNullOrEmpty(txtUserName.Text.Trim) Then
            txtUserName.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtPassword.Text.Trim) Then
            txtPassword.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtConfirmPassword.Text.Trim) Then
            txtConfirmPassword.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtAnswer.Text.Trim) Then
            txtAnswer.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtName.Text.Trim) Then
            txtAnswer.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtCuit.Text.Trim) Then
            txtCuit.Focus()
            _MsgBox.ShowMessage("ABM Usuarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If

        Return True
    End Function

    Private Function InsertUser() As Boolean
        Dim wNewUser As UserBE = Nothing

        If Not ValidateRequiredFields() Then Return False

        'Verifico que las contraseñas concuerden.
        If txtPassword.Text.Trim <> txtConfirmPassword.Text.Trim Then
            txtConfirmPassword.Focus()
            txtConfirmPassword.SelectAll()
            _MsgBox.ShowMessage("ABM Usuarios", "Las Contraseñas no concuerdan", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If

        'Creo la instancia del nuevo usuario.
        wNewUser = New UserBE
        With wNewUser
            'Nombre de usuario
            .UserName = txtUserName.Text.Trim
            'Encripto la contraseña creada
            .Password = wNewUser.EncryptPassword(txtPassword.Text.Trim)
            'Pregunta de seguridad
            .Question = New QuestionBE
            .Question.Id = cmbQuestion.SelectedValue
            'Perfil
            .Profile = New ProfileBE
            .Profile.Id = cmbProfile.SelectedValue
            'Respuesta
            .Answer = txtAnswer.Text.Trim
            'Nombre
            .Name = txtName.Text.Trim
            'Tipo de documento
            .DocumentType = New DocumentTypeBE
            .DocumentType.Id = cmbDocType.SelectedValue
            'Nro. documento
            .DocumentNumber = txtDocNumber.Text.Trim
            'Sexo
            .Sex = New SexBE
            .Sex.Id = cmbSex.SelectedValue
            'CUIT/L
            .Cuit = txtCuit.Text.Trim
            'País
            If cmbCountry.SelectedValue <> 0 Then '0 = Sin Selección
                .Country = New CountryBE
                .Country.Id = cmbCountry.SelectedValue
            End If
            'Provincia
            If cmbProvince.SelectedValue <> 0 Then '0 = Sin Selección
                .Province = New ProvinceBE
                .Province.Id = cmbProvince.SelectedValue
            End If
            'Ciudad
            If cmbCity.SelectedValue <> 0 Then '0 = Sin Selección
                .City = New CityBE
                .City.Id = cmbCity.SelectedValue
            End If
            .Direction = IIf(String.IsNullOrEmpty(txtDirection.Text.Trim), Nothing, txtDirection.Text.Trim)
            .PostalCode = IIf(String.IsNullOrEmpty(txtPostalCode.Text.Trim), Nothing, txtPostalCode.Text.Trim)
            .Phone = IIf(String.IsNullOrEmpty(txtPhone.Text.Trim), Nothing, txtPhone.Text.Trim)
            .Celphone = IIf(String.IsNullOrEmpty(txtCelphone.Text.Trim), Nothing, txtCelphone.Text.Trim)
            .Email = IIf(String.IsNullOrEmpty(txtEmail.Text.Trim), Nothing, txtEmail.Text.Trim)
        End With

        'Inserto el nuevo usuario
        _UserController.Insert(wNewUser)

        Return True
    End Function

    Private Function UpdateUser() As Boolean
        Dim wNewUser As UserBE = Nothing

        If Not ValidateRequiredFields() Then Return False

        'Verifico que las contraseñas concuerden.
        If txtPassword.Text.Trim <> txtConfirmPassword.Text.Trim Then
            txtConfirmPassword.Focus()
            txtConfirmPassword.SelectAll()
            _MsgBox.ShowMessage("ABM Usuarios", "Las Contraseñas no concuerdan", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If

        'Creo la instancia del nuevo usuario.
        wNewUser = New UserBE
        With wNewUser
            'Nombre de usuario
            .UserName = txtUserName.Text.Trim
            'Encripto la contraseña modificada
            .Password = wNewUser.EncryptPassword(txtPassword.Text.Trim)
            'Pregunta de seguridad
            .Question = New QuestionBE
            .Question.Id = cmbQuestion.SelectedValue
            'Perfil
            .Profile = New ProfileBE
            .Profile.Id = cmbProfile.SelectedValue
            'Respuesta
            .Answer = txtAnswer.Text.Trim
            'Nombre
            .Name = txtName.Text.Trim
            'Tipo de documento
            .DocumentType = New DocumentTypeBE
            .DocumentType.Id = cmbDocType.SelectedValue
            'Nro. documento
            .DocumentNumber = txtDocNumber.Text.Trim
            'Sexo
            .Sex = New SexBE
            .Sex.Id = cmbSex.SelectedValue
            'CUIT/L
            .Cuit = txtCuit.Text.Trim
            'País
            If cmbCountry.SelectedValue <> 0 Then '0 = Sin Selección
                .Country = New CountryBE
                .Country.Id = cmbCountry.SelectedValue
            End If
            'Provincia
            If cmbProvince.SelectedValue <> 0 Then '0 = Sin Selección
                .Province = New ProvinceBE
                .Province.Id = cmbProvince.SelectedValue
            End If
            'Ciudad
            If cmbCity.SelectedValue <> 0 Then '0 = Sin Selección
                .City = New CityBE
                .City.Id = cmbCity.SelectedValue
            End If
            .Direction = IIf(String.IsNullOrEmpty(txtDirection.Text.Trim), Nothing, txtDirection.Text.Trim)
            .PostalCode = IIf(String.IsNullOrEmpty(txtPostalCode.Text.Trim), Nothing, txtPostalCode.Text.Trim)
            .Phone = IIf(String.IsNullOrEmpty(txtPhone.Text.Trim), Nothing, txtPhone.Text.Trim)
            .Celphone = IIf(String.IsNullOrEmpty(txtCelphone.Text.Trim), Nothing, txtCelphone.Text.Trim)
            .Email = IIf(String.IsNullOrEmpty(txtEmail.Text.Trim), Nothing, txtEmail.Text.Trim)
        End With

        'Inserto el nuevo usuario
        _UserController.Update(wNewUser)

        Return True
    End Function

    Private Function CloseUserAccount() As Boolean
        Dim wUser As UserBE = Nothing
        Dim wMotive As String = String.Empty
        Dim wInputBox As frmInputVisorBox = Nothing

        If GridView1.RowCount = 0 Then Return False

        If _MsgBox.ShowMessage("ABM Usuarios", "¿Está Seguro de dar de baja al Usuario?",
                               frmMessage.MessageType.Question_,
                               frmMessage.MessageButtons.OkCancel) = frmMessage.MsgResult.Cancel Then
            Return False
        End If

        wInputBox = New frmInputVisorBox
        wMotive = wInputBox.ShowBox("Baja de Usuario", frmInputVisorBox.Behavior.Write, "Cese de Servicio")

        wUser = _Users.Find(Function(u) u.UserName = GridView1.GetFocusedRowCellValue("UserName"))
        wUser.EndDate = Date.Today
        wUser.AccountCloseMotive = wMotive
        _UserController.Update(wUser)
        Return True
    End Function

#End Region

End Class
